<template>
  <div>
    <!-- 面包屑 -->
    <Breadcrumb :crumbs='crumbs'/>
    <!-- 数据区域 -->
    <el-card class="box-card">
      <!-- 搜索区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="usersTable.queryStr" placeholder="请输入内容" clearable @clear='handlerQuery'
          @keyup.enter.native="handlerQuery">
            <el-button slot="append" icon="el-icon-search" @click="handlerQuery"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleAddUserBtn">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 列表区 -->
      <el-row>
        <el-table border style="width:100%"
          :data="usersTable.users">
          <el-table-column type='index' label="#"></el-table-column>
          <el-table-column prop="username"
            label="姓名">
          </el-table-column>
          <el-table-column prop="email"
            label="邮箱">
          </el-table-column>
          <el-table-column prop="mobile"
            label="电话">
          </el-table-column>
          <el-table-column prop="role_name"
            label="角色">
          </el-table-column>
          <el-table-column
            label="状态">
            <template v-slot:='scope'>
              <el-switch @change="handlerStateChange(scope.row)" v-model="scope.row.mg_state"></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope='scope'>
              <el-button type="primary" size="mini"
              icon="el-icon-edit"
               @click="handleEditBtn(scope.row)"></el-button>
              <el-button type="danger" size="mini"
              icon="el-icon-delete"
               @click="handleDeleteBtn(scope.row)"></el-button>
               <el-tooltip placement="top" content="分配角色" :enterable=false>
                <el-button type="warning" size="mini"
                icon="el-icon-star-off"
                @click="handleRoleBtn(scope.row)"></el-button>
               </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 分页控件 -->
      <el-row>
        <el-pagination layout="total, sizes, prev, pager, next, jumper"
         :total="usersTable.total"
         :page-size='usersTable.pagesize'
         :page-sizes='[1, 2, 10, 20, 100]'
         @size-change='handleSizeChange'
         @current-change='handleCurrentChange'
        ></el-pagination>
      </el-row>
    </el-card>
    <!-- 添加/修改弹框 -->
    <el-dialog width="30%"
     :title="dialogType === 1? '添加用户': '编辑用户'" :visible.sync='dialogVisible'>
      <el-form ref='userForm' :model="formData" :rules="formRules">
        <el-form-item label="用户名" label-width="80px" prop="username">
          <el-input :disabled="dialogType !== 1" v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="80px" prop="password">
          <el-input :disabled="dialogType !== 1" v-model="formData.password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" label-width="80px" prop="mobile">
          <el-input v-model="formData.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="80px" prop="email">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlerDialogSaveUser">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from './Breadcrumb.vue'
export default {
  data () {
    const mobileValidator = (rule, val, cb) => {
      const res = /^1[3456789][0-9]{9}$/.test(val)
      if (!res) cb(new Error('请输入正确的11位手机号码'))
      cb()
    }
    const emailValidator = (rule, val, cb) => {
      if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(val)) {
        cb(new Error('请输入正确的邮箱 如：abc@163.com'))
      }
      cb()
    }
    return {
      usersTable: {
        total: 0,
        pagenum: 1,
        pagesize: 10,
        queryStr: null,
        users: [{
          id: 1,
          role_name: 'role',
          username: 'name',
          create_time: 1511853015,
          mobile: '131',
          email: 'name@qq.com',
          mg_state: true
        }]
      },
      crumbs: [
        { path: '/home', title: '首页' },
        { title: '用户管理' },
        { title: '用户列表' }
      ],
      dialogVisible: false,
      dialogType: 1,
      formData: {},
      defaultFormData: {
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      formRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            min: 3, max: 10, message: '长度为3～10位', trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6, max: 16, message: '长度位6～16位', trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            validator: mobileValidator, trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            validator: emailValidator, trigger: 'blur'
          }
        ]
      }
    }
  },
  components: { Breadcrumb },
  methods: {
    async getUserList () {
      // 获取用户列表方法
      let query = '?pagenum=' + this.usersTable.pagenum + '&pagesize=' + this.usersTable.pagesize
      if (this.usersTable.queryStr) query += '&query=' + this.usersTable.queryStr
      const { data: res } = await this.axios.get('/private/v1/users' + query)
      if (!res || !res.data) return this.$message.error('获取用户列表失败')
      const pagesize = this.usersTable.pagesize
      const queryStr = this.usersTable.queryStr
      this.usersTable = { pagesize, queryStr, ...res.data }
    },
    async updateUserState (user) {
      // 更新用户状态
      const path = '/private/v1/users/' + user.id + '/state/' + user.mg_state
      const { data: res } = await this.axios.put(path)
      if (!res || !res.data || !res.meta || res.meta.status !== 200) {
        user.mg_state = !user.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新状态成功')
    },
    handleSizeChange (val) {
      // 分页大小变化
      console.log('handleSizeChange:', val)
      this.usersTable.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      // 分页当前页变化
      console.log('handleCurrentChange:', val)
      this.usersTable.pagenum = val
      this.getUserList()
    },
    handlerStateChange (row) {
      // 行 用户状态变化
      console.log('handlerStateChange:', row)
      this.updateUserState(row)
    },
    handlerQuery () {
      // 搜索按钮触发
      console.log('query:', this.usersTable.queryStr)
      this.getUserList()
    },
    handleAddUserBtn () {
      // 添加用户按钮处理
      this.dialogVisible = true
      this.dialogType = 1
      if (this.$refs.userForm) this.$refs.userForm.resetFields()
      this.formData = { ...this.defaultFormData }
    },
    handleEditBtn (user) {
      // 编辑按钮处理
      console.log(user)
      this.dialogVisible = true
      this.dialogType = 2
      // 清除验证信息
      if (this.$refs.userForm) this.$refs.userForm.resetFields()
      this.formData = {
        username: user.username,
        password: '******',
        mobile: user.mobile,
        email: user.email,
        id: user.id
      }
      console.log('copy:', this.formData, user)
    },
    async handleDeleteBtn (user) {
      // 删除按钮处理
      const confirmRes = await this.$confirm('确认删除该用户吗？', '删除确认', {
        confirmButtonText: '确认',
        cancelButtonText: '放弃删除',
        type: 'warning'
      }).catch(action => action)
      if (confirmRes !== 'confirm') return
      const path = '/private/v1/users/' + user.id
      const { data: res } = await this.axios.delete(path)
      console.log('delete res:', res)
      if (!res || !res.meta || res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    handlerDialogSaveUser () {
      // 用户弹框保存处理
      this.$refs.userForm.validate(async (valid) => {
        console.log(valid)
        if (!valid) return false
        if (this.dialogType === 1) {
          // 新增
          const { data: res } = await this.axios.post('/private/v1/users', this.formData)
          if (!res || !res.meta || res.meta.status !== 201) {
            console.log('save res:', res)
            return this.$message.error('添加用户失败')
          }
          this.$message.success('添加用户成功')
        } else {
          // 修改
          const params = { email: this.formData.email, mobile: this.formData.mobile }
          const { data: res } = await this.axios.put('/private/v1/users/' + this.formData.id, params)
          if (!res || !res.meta || res.meta.status !== 200) {
            console.log('modify res:', res)
            return this.$message.error('修改用户失败')
          }
          this.$message.success('修改用户成功')
        }
        this.dialogVisible = false
        this.getUserList()
      })
    }
  },
  created () {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>
.box-card {
  margin: 10px;
}

.el-row {
  margin-bottom: 20px;
}

.el-pagination {
  text-align: left;
}
</style>
